const mongoose = require('mongoose')
const jwt = require('jsonwebtoken')
const config = require('../config/index')

// 引入joi
const Joi = require('joi')
Joi.objectId = require('joi-objectid')(Joi)

// 定义user的schema结构
const userSchema = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        minlegth: 6,
        maxLength: 30,
        unique: true
    },
    // 用户名
    username: {
        type: String,
        required: true,
        minLength: 2,
        maxLength: 20
    },

    // 密码
    password: {
        type: String,
        required: true,
        minLength: 6,
        maxLength: 500,
        select: false  // 在使用find方法时，可以不返回密码
    },
    // mongodb会自动生成_id和__v两个字段
    __v: {
        type: Number,
        select: false
    }
})

// 生成token
userSchema.methods.generateToken = function () {
    return jwt.sign({
        _id: this._id
    },
        config.sceret,
        { expiresIn: '10d' }
    )
}

// 将schema转换成一个model
const User = mongoose.model('User', userSchema)

// 创建校验规则对象
function userValidator(data) {
    const schema = Joi.object({
        email: Joi.string().email().trim().lowercase().min(6).max(30).required().messages({
            "any.required": "缺少邮箱地址",
            "string.email": "邮箱格式错误"
        }),
        username: Joi.string().min(2).max(20).required().messages({
            "any.required": "缺少用户名",
            "string.base": "name必须为string类型",
            "string.min": "用户名至少需要2个字符",
            "string.max": "用户名最多不可超过20个字符"
        }),
        password: Joi.string().min(6).max(16).pattern(/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/).required().messages({
            "any.required": "缺少必选的参数",
            "string.min": "密码至少需要6个字符",
            "string.max": "密码最多不可超过16个字符",
            "string.pattern.base": "密码需要字母和数字"

        }),
        _id: Joi.objectId()
    })

    return schema.validate(data)
}

// Joi还可以实现自定义错误提示，通过messages方法，实现
module.exports = {
    User,
    userValidator
}